package nio.bytebuffer;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author ZH
 */
public class TestByteBuffer {
    public static void main(String[] args) {
        //获得FileChannel  1.输入输出流 2.RandomAccessFile
        try {
            FileChannel channel = new FileInputStream("data.txt").getChannel();
            //准备缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while (true){
                //从channel 中读取,从buffer中写入
                int len = channel.read(buffer);
                if (len == -1){
                    break; //没有内容了
                }
                //打印buffer
                buffer.flip();//切换到读模式
                while (buffer.hasRemaining()){ //检查是否还有剩余的数据
                    byte b = buffer.get();
                    System.out.print((char)b);
                }
                buffer.clear(); //切换到写模式
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
